package cn.bonoon.kernel.support;

import java.util.Date;
import java.util.regex.Pattern;

import javax.persistence.EntityManager;

import cn.bonoon.entities.TagEntity;
import cn.bonoon.kernel.util.StringHelper;

public final class TagGenerator {
	public String generate(EntityManager entityManager, Date now, String regex, String newTag, String oldTag){
		//if(StringHelper.isEmpty(newTag)) return null;
		Pattern pattern = Pattern.compile(regex);
		String[] nts = pattern.split(newTag);
		String[] ots;
		if(StringHelper.isNotEmpty(oldTag)){
			ots = pattern.split(oldTag);
		}else{
			ots = new String[0];
		}
		String ql = "update TagEntity x set x.count=x.count+1,x.lastQuoteAt=:lastQuoteAt where x.tagName=:tagName";
		NEXT : for(int i = 0; i < nts.length; i++){
			String tag = nts[i];
			for(int j = 0; j < ots.length; j++){
				if(tag.equals(ots[j])) continue NEXT;
			}
			if(entityManager.createQuery(ql)
					.setParameter("lastQuoteAt", now)
					.setParameter("tagName", tag)
					.executeUpdate() == 0){
				TagEntity te = new TagEntity();
				te.setCount(1);
				te.setCreateAt(now);
				te.setLastQuoteAt(now);
				te.setTagName(tag);
				entityManager.persist(te);
			}
		}
		return newTag;
	}
}
